package com.itheima.store.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.itheima.store.domain.BookCategory;
import com.itheima.store.domain.User;
import com.itheima.store.domain.Book;
import com.itheima.store.service.BookService;
import com.itheima.store.utils.BeanFactory;
import com.itheima.store.utils.UUIDUtils;

/**
 * 添加/编辑图书的Servlet:
 */
public class AddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user=(User) request.getSession().getAttribute("existUserAdmin");
		
		if("".equals(user)||user==null){
			request.setAttribute("msg", "登录过期，请重新登录！");
			request.getRequestDispatcher("/admin/index.jsp").forward(request, response);
		}else{
		try {
			// 创建一个Book的对象:
			Book book = new Book();
			// 创建磁盘文件项工厂.
			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			// 设置缓存区的大小: 如果文件的大小超过了缓冲区的大小,就会产生临时文件.
			diskFileItemFactory.setSizeThreshold(3 * 1024 * 1024);
			// 设置临时文件存放的路径:
			// diskFileItemFactory.setRepository(repository);
			// 获得核心解析类:ServletFileUpload
			ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
			fileUpload.setHeaderEncoding("UTF-8");// 解决中文文件名上传乱码.
			// fileUpload.setFileSizeMax(fileSizeMax); // 设置单个文件大小
			// fileUpload.setSizeMax(sizeMax); // 设置表单中的所有文件项的文件总大小
			// 解析request 返回List集合
			List<FileItem> list = fileUpload.parseRequest(request);
			// 获得每个部分:
			// 将遍历的值存入到一个Map集合中:
			Map<String,String> map = new HashMap<String,String>();
			String fileName="";
			for (FileItem fileItem : list) {
				//　判断普通项和文件上传项：
				if(fileItem.isFormField()){
					// 普通项
					String name = fileItem.getFieldName();
					String value = fileItem.getString("UTF-8"); // 解决的是普通项的中文乱码.
					System.out.println(name+"   "+value);
					map.put(name, value);
				}else{
					// 文件上传项 
					// 获得文件名:
					fileName = fileItem.getName();
					if(!"".equals(fileName)){
						System.out.println("文件名:"+fileName);
						//获取图片的名称
						if(fileName.contains("\\")){
							fileName = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length()) ; 
						}
						
						// 获得文件的输入流:
						InputStream is = fileItem.getInputStream();
						// 获得文件要上传的路径:
						String path = this.getServletContext().getRealPath("/books/bookimg");
						//String currentPath=getClass().getResource(".").getFile().toString(); //当前目录路径
						OutputStream os = new FileOutputStream(path+"/"+fileName);
						int length = 0;
						byte[] b= new byte[1024];
						while((length = is.read(b))!=-1){
							os.write(b, 0, length);
						}
						is.close();
						os.close();
					}
				}
			}
			// 封装数据:
			
				BeanUtils.populate(book, map);
				if(!"".equals(fileName)){
					book.setBook_image("books/bookimg/"+fileName);
				}
				BookService bookService = (BookService) BeanFactory.getBean("bookService");
				String iid = map.get("book_id");
				Date date=new Date();                             
		        SimpleDateFormat temp=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		        String date1=temp.format(date);  
		        Date date2 = null;
				try {
					date2 = temp.parse(date1);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				if("".equals(iid)||iid==null){
					
					String user_id = user.getUser_id();
					String user_name = user.getUser_name();
					book.setCreatePerson_id(user_id);
					book.setCeratePerson(user_name);
					book.setBook_id(UUIDUtils.getUUID());
					book.setBook_createTime(date2);
				//	book.setBook_createTime(new Date());
					book.setIsunder(0);
					BookCategory category = new BookCategory();
					category.setCategory_id(map.get("book_category_id"));
					//book.setBook_category_id(book_category_id);
					// 存入到数据库:
					bookService.save(book);
					
			}
			else{
				// 存入到数据库:
				bookService.update(book);
				}
			
			
			// 页面跳转:
			response.sendRedirect(request.getContextPath()+"/AdminBookServlet?method=findByPage&currPage=1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
